/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This code is derived from the project ojoverse (2008, same author)
 * under the license GPL2. See <http://www.gnu.org/licenses/>.
 */

package org.ix.net;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ix.data.manager.P2PBroker;
import org.ix.utils.Serialize;

public abstract class BaseP2PServlet extends BaseServlet {

    protected PrintWriter out = null;
    protected P2PBroker broker = null;

    protected void process(HttpServletRequest req, HttpServletResponse res) {
        res.setContentType("text/html;charset=UTF-8");
        try {
            out = res.getWriter();
        } catch (IOException ex) {
            Logger.getLogger(BaseP2PServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        broker = (P2PBroker) getServletContext().getAttribute(prop("p2pBrokerSessionName"));
        if (broker == null) {
            checkBroker();
        }

        serve(req, res);
        if (out != null) {
            out.close();
        }
    }

    private void checkBroker() {
        broker = (P2PBroker) Serialize.readFromFile(prop("dataDir") + prop("p2pBrokerFileName"));
        if (broker == null) {
            broker = new P2PBroker();
        }
    }

    protected abstract void serve(HttpServletRequest request, HttpServletResponse response);
}
